'use strict';

const _ = require('lodash');

exports.index = async ctx => {
  const { query } = ctx.request;
  let pageSize = 10;
  if (query.pageSize) pageSize = Number(query.pageSize);
  const where = {};
  const { id, category } = query;
  if (id) where.id = id;
  if (category) where.category = category;
  const options = {
    limit: pageSize,
    offset: query.currentPage ? pageSize * (query.currentPage - 1) : 0,
    order: [
      [ 'id', 'DESC' ],
    ],
    raw: true,
    where,
  };
  const {
    count: total, rows: list,
  } = await ctx.model.Article.findAndCountAll(options);
  ctx.body = {
    list,
    pagination: {
      total,
      pageSize,
      current: parseInt(query.currentPage, 10) || 1,
    },
  };
};

exports.create = async ctx => {
  if (ctx.state.user.role === 'admin') {
    ctx.validate({
      title: { type: 'string' },
      content: { type: 'string' },
      category: { type: 'string' },
      status: { type: 'string', require: false },
      imageHash: { type: 'string', max: 28, min: 28, required: false },
    });
    await ctx.service.file.record('image', ctx.request.body.imageHash);
    ctx.body = await ctx.model.Article.create(_.pick(
      ctx.request.body,
      [ 'title', 'content', 'category', 'status', 'imageHash' ]
    ));
  }
};

exports.show = async ctx => {
  const options = { raw: true };
  const article = await ctx.model.Article.findByPk(ctx.params.id, options);
  if (article) {
    ctx.body = article;
  } else {
    ctx.status = 404;
  }
};

exports.update = async ctx => {
  if (ctx.state.user.role === 'admin') {
    const article = await ctx.model.Article.findByPk(ctx.params.id);
    if (article) {
      ctx.validate({
        title: { type: 'string', required: false },
        content: { type: 'string', required: false },
        category: { type: 'string', required: false },
        status: { type: 'string', require: false },
        imageHash: { type: 'string', max: 28, min: 28, required: false },
      });
      const { imageHash } = ctx.request.body;
      if (imageHash) ctx.service.file.record('image', imageHash);
      ctx.body = await article.update(_.pickBy(
        _.pick(
          ctx.request.body,
          [ 'title', 'content', 'category', 'status', 'imageHash' ]
        ),
        value => value !== null
      ));
    } else {
      ctx.status = 404;
    }
  }
};

exports.destroy = async ctx => {
  const article = await ctx.model.Article.findByPk(ctx.params.id);
  if (article) {
    await article.destroy();
    ctx.status = 204;
  } else {
    ctx.status = 404;
  }
};
